package org.jeecg.hr.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.autopoi.poi.excel.ExcelImportUtil;
import org.jeecg.autopoi.poi.excel.def.NormalExcelConstants;
import org.jeecg.autopoi.poi.excel.entity.ExportParams;
import org.jeecg.autopoi.poi.excel.entity.ImportParams;
import org.jeecg.autopoi.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.hr.entity.Personnel;
import org.jeecg.hr.entity.PersonnelInsuranceItem;
import org.jeecg.hr.entity.PersonnelSalaryItem;
import org.jeecg.hr.service.PersonnelInsuranceItemService;
import org.jeecg.hr.service.PersonnelSalaryItemService;
import org.jeecg.hr.service.PersonnelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 个人薪酬
 * @Author: MxpIO
 */
@Api(tags = "个人薪酬")
@RestController
@RequestMapping("/hr/salary/personnel")
@Slf4j
public class PersonnelController extends JeecgController<Personnel, PersonnelService> {

	@Autowired
	private PersonnelService personnelService;

	@Autowired
	private PersonnelInsuranceItemService personnelInsuranceItemService;
	
	@Autowired
	private PersonnelSalaryItemService personnelSalaryItemService;

	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * 
	 * @param insuranceTemplate
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "个人薪酬-分页列表查询")
	@ApiOperation(value = "个人薪酬-分页列表查询", notes = "个人薪酬-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(Personnel personnel,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		QueryWrapper<Personnel> queryWrapper = QueryGenerator.initQueryWrapper(personnel,
				req.getParameterMap());
		Page<Personnel> page = new Page<Personnel>(pageNo, pageSize);
		IPage<Personnel> pageList = personnelService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 * 添加
	 *
	 * @param insuranceTemplate
	 * @return
	 */
	@AutoLog(value = "个人薪酬-添加(主从)")
	@ApiOperation(value = "个人薪酬-添加(主从)", notes = "个人薪酬-添加(主从)")
	@PostMapping(value = "/addWithChildren")
	public Result<?> addWithChildren(@RequestBody Personnel personnel) {
		personnelService.savePersonnelWithDetail(personnel);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 *
	 * @param insuranceTemplate
	 * @return
	 */
	@AutoLog(value = "个人薪酬-编辑(主从)")
	@ApiOperation(value = "个人薪酬-编辑(主从)", notes = "个人薪酬-编辑(主从)")
	@PutMapping(value = "/editWithChildren")
	public Result<?> editWithChildren(@RequestBody Personnel personnel) {
		Personnel personnelEntity = personnelService.getById(personnel.getId());
		if (personnelEntity == null) {
			return Result.error("未找到对应数据");
		}
		personnelService.updatePersonnelWithDetail(personnel);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * 
	 * @param id
	 * @return
	 */
	@AutoLog(value = "个人薪酬-通过id删除")
	@ApiOperation(value = "个人薪酬-通过id删除", notes = "个人薪酬-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
		personnelService.delPersonnel(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "个人薪酬-批量删除")
	@ApiOperation(value = "个人薪酬-批量删除", notes = "个人薪酬-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		personnelService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 导出
	 * 
	 * @return
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, Personnel personnel) {
		return super.exportXls(request, personnel, Personnel.class, "个人薪酬");
	}

	/**
	 * 导入
	 * 
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, Personnel.class);
	}
	/*---------------------------------主表处理-end-------------------------------------*/

	/*--------------------------------子表处理-个人薪酬项目明细-begin----------------------------------------------*/
	/**
	 * 通过主表Username查询
	 * 
	 * @return
	 */
	@AutoLog(value = "个人薪酬项目明细-通过Username查询")
	@ApiOperation(value = "个人薪酬项目明细-通过Username查询", notes = "个人薪酬项目明细-通过Username查询")
	@GetMapping(value = "/listPersonnelSalaryItemByUsername")
	public Result<?> listPersonnelSalaryItemByUsername(PersonnelSalaryItem personnelSalaryItem,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {

		Object username = req.getParameter("username");
		if(username == null){
			return Result.OK();
		}
		QueryWrapper<PersonnelSalaryItem> queryWrapper = QueryGenerator.initQueryWrapper(personnelSalaryItem,
				req.getParameterMap());
		Page<PersonnelSalaryItem> page = new Page<PersonnelSalaryItem>(pageNo, pageSize);
		IPage<PersonnelSalaryItem> pageList = personnelSalaryItemService.page(page, queryWrapper);
		personnelSalaryItemService.handleTransientVariable(pageList.getRecords());
		return Result.OK(pageList);
	}

	/**
	 * 添加
	 * 
	 * @param personnelSalaryItem
	 * @return
	 */
	@AutoLog(value = "个人薪酬项目明细-添加")
	@ApiOperation(value = "个人薪酬项目明细-添加", notes = "个人薪酬项目明细-添加")
	@PostMapping(value = "/addPersonnelSalaryItem")
	public Result<?> addPersonnelSalaryItem(@RequestBody PersonnelSalaryItem personnelSalaryItem) {
		personnelSalaryItemService.save(personnelSalaryItem);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 * 
	 * @param personnelSalaryItem
	 * @return
	 */
	@AutoLog(value = "个人薪酬项目明细-编辑")
	@ApiOperation(value = "个人薪酬项目明细-编辑", notes = "个人薪酬项目明细-编辑")
	@PutMapping(value = "/editPersonnelSalaryItem")
	public Result<?> editPersonnelSalaryItem(@RequestBody PersonnelSalaryItem personnelSalaryItem) {
		personnelSalaryItemService.updateById(personnelSalaryItem);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * 
	 * @param id
	 * @return
	 */
	@AutoLog(value = "个人薪酬项目明细-通过id删除")
	@ApiOperation(value = "个人薪酬项目明细-通过id删除", notes = "个人薪酬项目明细-通过id删除")
	@DeleteMapping(value = "/deletePersonnelSalaryItem")
	public Result<?> deletePersonnelSalaryItem(@RequestParam(name = "id", required = true) String id) {
		personnelSalaryItemService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "个人薪酬项目明细-批量删除")
	@ApiOperation(value = "个人薪酬项目明细-批量删除", notes = "个人薪酬项目明细-批量删除")
	@DeleteMapping(value = "/deleteBatchPersonnelSalaryItem")
	public Result<?> deleteBatchPersonnelSalaryItem(@RequestParam(name = "ids", required = true) String ids) {
		personnelSalaryItemService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 导出
	 * 
	 * @return
	 */
	@RequestMapping(value = "/exportPersonnelSalaryItem")
	public ModelAndView exportPersonnelSalaryItem(HttpServletRequest request,
			PersonnelSalaryItem personnelSalaryItem) {
		// Step.1 组装查询条件
		QueryWrapper<PersonnelSalaryItem> queryWrapper = QueryGenerator.initQueryWrapper(personnelSalaryItem,
				request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<PersonnelSalaryItem> pageList = personnelSalaryItemService.list(queryWrapper);
		List<PersonnelSalaryItem> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(item.getId()))
					.collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "个人薪酬项目明细"); // 此处设置的filename无效
																// ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, PersonnelSalaryItem.class);
		mv.addObject(NormalExcelConstants.PARAMS,
				new ExportParams("个人薪酬项目明细报表", "导出人:" + sysUser.getRealname(), "个人薪酬项目明细"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

	/**
	 * 导入
	 * 
	 * @return
	 */
	@RequestMapping(value = "/importPersonnelSalaryItem/{username}")
	public Result<?> importPersonnelSalaryItem(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("username") String username) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<PersonnelSalaryItem> list = ExcelImportUtil.importExcel(file.getInputStream(),
						PersonnelSalaryItem.class, params);
				for (PersonnelSalaryItem temp : list) {
					temp.setUsername(username);
				}
				long start = System.currentTimeMillis();
				personnelSalaryItemService.saveBatch(list);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.OK("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	/*--------------------------------子表处理-个人薪酬项目明细-end----------------------------------------------*/
	
	/*--------------------------------子表处理-个人社保明细-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * 
	 * @return
	 */
	@AutoLog(value = "个人社保明细-通过Username查询")
	@ApiOperation(value = "个人社保明细-通过Username查询", notes = "个人社保明细-通过Username查询")
	@GetMapping(value = "/listPersonnelInsuranceItemByUsername")
	public Result<?> listPersonnelInsuranceItemByUsername(PersonnelInsuranceItem personnelInsuranceItem,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {

		Object username = req.getParameter("username");
		if(username == null){
			return Result.OK();
		}
		QueryWrapper<PersonnelInsuranceItem> queryWrapper = QueryGenerator.initQueryWrapper(personnelInsuranceItem,
				req.getParameterMap());
		Page<PersonnelInsuranceItem> page = new Page<PersonnelInsuranceItem>(pageNo, pageSize);
		IPage<PersonnelInsuranceItem> pageList = personnelInsuranceItemService.page(page, queryWrapper);
		personnelInsuranceItemService.handleTransientVariable(pageList.getRecords());
		return Result.OK(pageList);
	}

	/**
	 * 添加
	 * 
	 * @param personnelInsuranceItem
	 * @return
	 */
	@AutoLog(value = "个人社保明细-添加")
	@ApiOperation(value = "个人社保明细-添加", notes = "个人社保明细-添加")
	@PostMapping(value = "/addPersonnelInsuranceItem")
	public Result<?> addPersonnelInsuranceItem(@RequestBody PersonnelInsuranceItem personnelInsuranceItem) {
		personnelInsuranceItemService.save(personnelInsuranceItem);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 * 
	 * @param personnelInsuranceItem
	 * @return
	 */
	@AutoLog(value = "个人社保明细-编辑")
	@ApiOperation(value = "个人社保明细-编辑", notes = "个人社保明细-编辑")
	@PutMapping(value = "/editPersonnelInsuranceItem")
	public Result<?> editPersonnelInsuranceItem(@RequestBody PersonnelInsuranceItem personnelInsuranceItem) {
		personnelInsuranceItemService.updateById(personnelInsuranceItem);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * 
	 * @param id
	 * @return
	 */
	@AutoLog(value = "个人社保明细-通过id删除")
	@ApiOperation(value = "个人社保明细-通过id删除", notes = "个人社保明细-通过id删除")
	@DeleteMapping(value = "/deletePersonnelInsuranceItem")
	public Result<?> deletePersonnelInsuranceItem(@RequestParam(name = "id", required = true) String id) {
		personnelInsuranceItemService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "个人社保明细-批量删除")
	@ApiOperation(value = "个人社保明细-批量删除", notes = "个人社保明细-批量删除")
	@DeleteMapping(value = "/deleteBatchPersonnelInsuranceItem")
	public Result<?> deleteBatchPersonnelInsuranceItem(@RequestParam(name = "ids", required = true) String ids) {
		personnelInsuranceItemService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 导出
	 * 
	 * @return
	 */
	@RequestMapping(value = "/exportPersonnelInsuranceItem")
	public ModelAndView exportPersonnelInsuranceItem(HttpServletRequest request,
			PersonnelInsuranceItem personnelInsuranceItem) {
		// Step.1 组装查询条件
		QueryWrapper<PersonnelInsuranceItem> queryWrapper = QueryGenerator.initQueryWrapper(personnelInsuranceItem,
				request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<PersonnelInsuranceItem> pageList = personnelInsuranceItemService.list(queryWrapper);
		List<PersonnelInsuranceItem> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(item.getId()))
					.collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "个人社保明细"); // 此处设置的filename无效
																// ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, PersonnelInsuranceItem.class);
		mv.addObject(NormalExcelConstants.PARAMS,
				new ExportParams("个人社保明细报表", "导出人:" + sysUser.getRealname(), "个人社保明细"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

	/**
	 * 导入
	 * 
	 * @return
	 */
	@RequestMapping(value = "/importPersonnelInsuranceItem/{username}")
	public Result<?> importPersonnelInsuranceItem(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("username") String username) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<PersonnelInsuranceItem> list = ExcelImportUtil.importExcel(file.getInputStream(),
						PersonnelInsuranceItem.class, params);
				for (PersonnelInsuranceItem temp : list) {
					temp.setUsername(username);
				}
				long start = System.currentTimeMillis();
				personnelInsuranceItemService.saveBatch(list);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.OK("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	/*--------------------------------子表处理-个人社保明细-end----------------------------------------------*/
}
